﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Threading;
using MyFirstWPF.ViewModel;
using MaterialDesignThemes.Wpf;
using MyFirstWPF.View.Compnent;

namespace MyFirstWPF.View
{
    /// <summary>
    /// Window2.xaml 的交互逻辑
    /// </summary>
    public partial class Window2 : Window
    {
        public Window2()
        {
            InitializeComponent();

            // 异步检测是否有task需要提醒
            Task.Run(() =>
            {
                // 紧急任务在30，10，5分钟提醒； 一般任务在5分钟提醒
                // 以秒来记，方便计算
                Dictionary<TaskInfo.TaskLevel, List<int>> noticeSpanMap = new Dictionary<TaskInfo.TaskLevel, List<int>>
                {
                    {TaskInfo.TaskLevel.Emergency,new List<int>{ 1800,600,300} },
                    {TaskInfo.TaskLevel.Normal,new List<int>{300} }
                };

                using (var db = new StudyPlanDb(Page1.dbPath))
                {
                    while (true)
                    {                       
                        Thread.Sleep(3000); 

                        List<TaskInfo> taskInfos = db.Tasks.Where(x => x.userId == LoginView.myId).ToList();
                        DateTime now = DateTime.Now;
                        foreach(TaskInfo task in taskInfos)
                        {
                            // 结束时间在现在之前，任务已结束，跳过检测
                            if(task.GetEndTime() < now)
                            {
                                continue;
                            }

                            // 检测任务是否要开始，只有任务还没有开始才提醒
                            if (task.GetStartTime() > now)
                            {
                                TimeSpan span = task.GetStartTime() - now;
                                TimeSpan lastNoticeSpan = task.GetStartTime() - task.GetLastNoticeTime();
                                List<int> noticeSpans = noticeSpanMap[task.Level];
                                foreach (int i in noticeSpans)
                                {
                                    // 需要保证现在的时间距任务结束在范围内，同时上次提醒的时间距任务结束在范围外
                                    // 如果上次提醒的时间距任务结束在范围内，说明该范围已经提醒过
                                    if (span.TotalSeconds <= i && lastNoticeSpan.TotalSeconds > i)
                                    {
                                        // 修改一下上次提醒时间（就是现在） 
                                        task.SetLastNoticeTime(now);
                                        db.Update(task);
                                        // 显示dialog

                                        Dispatcher.Invoke(() =>
                                        {
                                            DialogHost.OpenDialogCommand.Execute(new NoticeTask(task, 0), null);
                                        });                                        
                                        break;
                                    }
                                }
                            }
                            
                            // 检测结束时写日志
                            if((task.GetEndTime() - now).Duration().TotalSeconds <= 3)
                            {
                                int cnt = db.Diarys.Where(x => x.TaskId == task.Id).Count();
                                // 如果没有写过日志才弹写日志的框框
                                if (cnt == 0)
                                {
                                    Dispatcher.Invoke(() =>
                                    {                       
                                        DialogHost.OpenDialogCommand.Execute(new AddDiary(task), null);
                                    });
                                }
                            }
                        }

                    }
                }
            });
        }

        // 获取只剩小时分钟和秒的时间，每日任务的操作不关心日期
        public static DateTime GetHHMMSS(DateTime time)
        {
            DateTime res = DateTime.MinValue;
            return res.AddHours(time.Hour).AddMinutes(time.Minute).AddSeconds(time.Second);
        }

        private void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private void frame1_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {

        }

        private void TabItem_Selected(object sender, RoutedEventArgs e)
        {
            frame1.Refresh();
            frame2.Refresh();
            frame3.Refresh();
            frame4.Refresh();
        }
    }
}
